import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutterlib/common/datacenter/channel_data_center.dart';
import 'package:flutterlib/common/datacenter/user_center.dart';
import 'package:flutterlib/common/utils/utils.dart';


class ResponseInterceptors extends InterceptorsWrapper {
  @override
  onResponse(Response response) async {
    RequestOptions options = response.request;
    // trueDebugPrint("flutterting response option " + options.headers.toString());
    Headers headers = response.headers;
    trueDebugPrint("flutterting response headers " + headers.toString());

    if (options.responseType == ResponseType.bytes ||
        options.responseType == ResponseType.stream) {
      return response;
    }
    if (response?.statusCode == 200) {
      var data;
      if(response.data is String){
        data = jsonDecode(response.data.toString())["data"];
      }else{
        data = response.data["data"];
      }
      if (data != null) {
        return data;
      } else {
        //如果是有些如文章的接口，没有code返回的，那么直接返回response
        if(response.data is String){
          return response;
        }
        //如果data为null但是有code，但不是200就抛出异常
        var code = (response.data ?? const {'code': 200})["code"];
        if (code == null || code == 200) {
          return response;
        } else {
          throw DioError(
              request: response.request,
              response: response,
              error: response.data["message"] ?? code);
        }
      }
    }  else{
      throw DioError(
          request: response.request,
          response: response,
          error: response.data["message"] ?? response?.statusCode);
    }

  }
}
